package com.project.webpage.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.project.webpage.entity.WebLog;
import com.project.webpage.service.WebLogService;
import com.project.webpage.util.NetworkUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect // 表示这是一个切面
@Component // 托管到spring容器中
public class AccessAspect {

    @Resource
    WebLogService webLogService;

    // 定义切点 匹配Controller中的TagLog
    @Pointcut("@annotation(TagLog)")
    public void init() {
    }

    // 使用后置增强，在方法正确执行后执行
    @AfterReturning("init()")
    public void record(JoinPoint joinPoint) throws Exception {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        TagLog annotation = method.getAnnotation(TagLog.class);
        if (annotation != null) {
            WebLog webLog = new WebLog();
            webLog.setOperation(annotation.operation());
            webLog.setContent(annotation.content());
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request  = servletRequestAttributes.getRequest();
            webLog.setCreateUser(request.getHeader("user"));
            webLog.setUrl(request.getRequestURI());
            webLog.setIp(NetworkUtil.getIpAddress(request));
            // 获取目标方法参数
            Object[] args = joinPoint.getArgs();
            if (args != null && args.length > 0) {
                webLog.setParams(JSON.toJSONStringWithDateFormat(args[0],"yyyy-MM-dd HH:mm:ss", new SerializerFeature[0]));
            }
            webLog.setCreateTime(new Date());
            webLogService.insert(webLog);
        }
    }
}
